package com.test.springboot.config.datasource;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Author: Mone xia
 * @Description jpa数据源
 * @Date Created in 上午 9:47 2017/12/28 0028
 * @Modified By:
 */
@Configuration
@MapperScan(basePackages = "com.test.springboot.dao3", sqlSessionTemplateRef = "oneJdbcTemplate")
public class DataSourceConfig {
    @Value("${jdbc.ds3.driverClassName}")
    private String driver;

    @Value("${jdbc.ds3.url}")
    private String url;

    @Value("${jdbc.ds3.username}")
    private String username;

    @Value("${jdbc.ds3.password}")
    private String password;

    @Bean(name = "oneDataSource")
    public DataSource oneDataSource() {
        DruidXADataSource dataSource = new DruidXADataSource();
        //DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "test3SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/test/springboot/dao/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "oneJdbcTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("test3SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
